package java高并发核心编程.多线程.顺序执行;

//ABCABC...
public class Demo1 {
    private static volatile int num;
    private static final Object lock = new Object();
    private static final int MAX = 10;

    public static void printABC(int targetNum) {
        for (int i = 0; i < MAX; i++) {
            synchronized (lock) {
                while (num % 3 != targetNum) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                num++;
                System.out.print(Thread.currentThread().getName());
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            printABC(0);
        }, "A").start();
        new Thread(() -> {
            printABC(1);
        }, "B").start();
        new Thread(() -> {
            printABC(2);
        }, "C").start();
    }
}
